package com.onlyxiahui.framework.json.validator.impl;

import com.alibaba.fastjson.JSONObject;
import com.onlyxiahui.framework.json.validator.Validator;
import com.onlyxiahui.framework.json.validator.ValidatorError;
import com.onlyxiahui.framework.json.validator.ValidatorResult;

/**
 * 
 * Date 2018-12-26 15:49:52<br>
 * Description
 * 
 * @author XiaHui<br>
 * @since 1.0.0
 */
public class JsonNotBlankValidator implements Validator<JSONObject, Object> {

	@Override
	public String getKey() {
		return "notBlank";
	}

	@Override
	public ValidatorResult valid(JSONObject data, Object attribute, Object judge, String code, String message) {
		ValidatorResult vr = null;
		String text = (null == attribute) ? null : attribute.toString();
		boolean mark = isNotBlank(text);

		if (!mark) {
			vr = new ValidatorResult();
			vr.setErrorCode(code == null ? this.getCode() : code);
			vr.setMessage(message == null ? this.getMessage() : message);
		}
		return vr;
	}

	public String getCode() {
		return ValidatorError.is_blank;
	}

	public String getMessage() {
		return "不能为空！";
	}

	private boolean isNotBlank(final CharSequence cs) {
		return !isBlank(cs);
	}

	private boolean isBlank(final CharSequence cs) {
		int strLen;
		if (cs == null || (strLen = cs.length()) == 0) {
			return true;
		}
		for (int i = 0; i < strLen; i++) {
			if (Character.isWhitespace(cs.charAt(i)) == false) {
				return false;
			}
		}
		return true;
	}

}
